#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/10/12 1:01 下午
# file: security.py
"""
from datetime import datetime, timedelta
from typing import Any, Union

from app.config.setting import settings
from jose import jwt
from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# 算法
ALGORITHM = "HS256"


def create_access_token(
    subject: Union[str, Any], expires_delta: timedelta = None
) -> str:
    """
    创建 JWT token
    :param subject: 一般是 id
    :param expires_delta: 过期时间
    :return:
    """
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        # 如果没有传，则拿 Settings 的过期时间
        expire = datetime.utcnow() + timedelta(
            minutes=settings.access_token_expire_minutes
        )
    # 准备加密的数据
    to_encode = {"exp": expire, "sub": str(subject)}
    # 生成 jwt token
    encode_jwt = jwt.encode(to_encode, settings.secret_key, algorithm=ALGORITHM)
    return encode_jwt


# 验证密码
def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)


# hash 加密
def get_password_hash(password: str) -> str:
    return pwd_context.hash(password)
